package com.neusoft.weekreport.component.downloadFile;

import java.net.URLEncoder;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class DownLoadFileController {

    private Logger log = LoggerFactory.getLogger(DownLoadFileController.class);

    /**
     * @Author liu.jiaming@neusoft.com
     * @Date 10:44 2022/12/7
     * @Param [response, req]
     * @return void
     * todo 下载文件
     **/
    @PostMapping("/downLoadFile")
    @ResponseBody
    public void downLoadFile(HttpServletResponse response, @RequestBody DownLoadFileReq req) {
        log.info("-----进入到下载后台方法-----");
        response.setHeader("Content-Type", "application/octet-stream");
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream out = null;
        FileInputStream fin = null;
        try {
            File file = new File(req.getPath());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(req.getPath(), "UTF-8"));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            fin = new FileInputStream(file);
            out = response.getOutputStream();
            IOUtils.copy(fin, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
